const net = require('net')
// const server = net.createServer((socket) => {
// console.log(socket);
//     socket.on('data', (data) => {
//         socket.write(data)
//     })
// })

// server.on('error', err => {
//     throw err
// })

// server.listen('6527', () => {
//     console.log('启动了');
// })

const server = new net.createServer()
let clients = {}
let clientName = 0
server.on('connection', (client) => {  //client其实就是socket  而且是一个对象
    client.name = ++clientName
    clients[client.name] = client
    client.on('data', (msg) => {
        // 客户端传来：+msg
        Broadcast(client, msg.toString())
    })
    client.on('error', (e) => {
        console.log('client error' + e);
        client.end()
    })
    client.on('close', (data) => { //前端end后端就可以获取
        delete clients[client.name]
        console.log(client.name + '下线了');
    })

})
server.listen('6527', () => {
    console.log('启动了');
})
// 很多个用户 其中一个用户说话了 其他人都要收到
function Broadcast(client, msg) {
    for (var key in clients) {
        clients[key].write(client.name + '说' + msg)
    }
}